package departmentservice

import (
	"fmt"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/data"
	"yunj/pkg/yunj/app/enum/admin/departmentenum"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/util"
)

// 获取正常部门岗位枚举选项
func GetNormalPostionTableColOptions() (options []builderdto.TableColOption, err error) {
	var items []*model.AdminDepartmentPostion
	tablePrefix := global.Config.Database.TablePrefix
	err = global.MySQL.Table(tablePrefix+"admin_department_postion dp").
		Joins("JOIN "+tablePrefix+"admin_department as d on dp.department_id = d.id").
		Joins("JOIN "+tablePrefix+"admin_postion as p on dp.postion_id = p.id").
		Select("dp.id", "dp.type", "dp.department_id", "p.name as postion_name").
		Where("dp.state = ? and d.state = ? and p.state = ?", stateenum.NORMAL, stateenum.NORMAL, stateenum.NORMAL).Order("d.sort asc,p.sort asc").Find(&items).Error
	if err != nil {
		err = fmt.Errorf("获取正常部门岗位枚举选项数据查询异常！%v", err)
		return
	}

	departmentMap := data.Department.GetNormalDepartmentMap()
	options = make([]builderdto.TableColOption, 0, len(items))
	for _, item := range items {
		label := fmt.Sprintf("【%s】%s", departmentenum.PostionTypeByValue(item.Type).GetDesc(), item.PostionName)
		fullLabel := label
		if department, exists := departmentMap[item.DepartmentId]; exists {
			fullLabel = department.FullName + "/" + fullLabel
		}
		options = append(options, builderdto.TableColOption{
			Value:     item.Id,
			Label:     label,
			FullLabel: fullLabel,
			BgColor:   util.RandomHexColor("#ffffff"),
		})
	}
	return
}
